const router = require('koa-router')()
const topik = require('../model/topik');

router.get('/han', async (ctx, next) => {
    var { pageSize, count } = ctx.query;
    if (!pageSize) {
        pageSize = 10;
    }
    if (!count) {
        count = 0;
    }

    let msg = await topik.find({}).limit(parseInt(pageSize)).skip(parseInt(count)).exec();
    ctx.body = {
        title: 'han',
        msg: msg
    }
})

router.post('/han', async (ctx, next) => {
    //console.log(this.params, ctx.query, ctx.request.body);

    var { cn, ko, nature, note, newnote } = ctx.request.body;
    if (cn && ko && nature) {
        let one = await topik.findOne({ cn: cn, ko: ko }).exec();
        if (one) {
            ctx.body = { msg: '已存在' }
        } else {
            let msg = await new topik({
                cn: cn,
                ko: ko,
                nature: nature,
                note: note,
                newnote: newnote
            }).save();
            ctx.body = { msg: msg };
        }
    }
})

router.put('/han', async (ctx, next) => {
    var { cn, ko, nature, note, newnote, id } = ctx.request.body;
    if (id && cn && ko && nature) {
        let one = await topik.findById(id).exec();
        if (one) {
            let msg = await topik.findByIdAndUpdate(id, {
                cn: cn,
                ko: ko,
                nature: nature,
                note: note,
                newnote: newnote
            })
            ctx.body = {
                title: 'han',
                msg: msg
            }
        } else {
            ctx.body = { msg: '不存在' }
        }
    }


})

router.delete('/han', async (ctx, next) => {
    var id = ctx.request.body.id;
    if (id) {
        let msg = await topik.findByIdAndDelete(id);
        ctx.body = {
            title: 'han',
            msg: msg
        }
    } else {
        ctx.body = {
            title: 'han'
        }
    }

})


module.exports = router